package cn.itsource.product.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.product.domain.Product;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    //分页查询接口
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery productQuery){
        return productService.queryPage(productQuery);
    }

    //分页查询接口---主要是用来给普通用户展示数据
    @PostMapping("/list")
    public PageList<Product> queryPageList(@RequestBody ProductQuery productQuery){
        //查询上架的产品
        productQuery.setState(1);
        return productService.queryPage(productQuery);
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Product product){
        try {
            if(product.getId() == null){
                productService.add(product);
            }else{
                productService.update(product);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    @PatchMapping
    //如果前端传递的数据是json数组 - 后端可以用数组或集合都可以接受
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            productService.onSale(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    @GetMapping("/{id}")
    public AjaxResult getProductById(@PathVariable("id") Long id){
        Product product = productService.findOne(id);
        return AjaxResult.me().setResultObject(product);
    }
}
